import { Command } from '../constant';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      // let { user } = Taro.getStorageSync('b2b-wechat@login')
      // if (user) {
      this.findDetail()
      this.findCommentList()
      // }
    },
    /**
     * 查询帖子详情
     */
    async findDetail() {
      let { user } = Taro.getStorageSync('b2b-wechat@login')
      let { id, type } = getCurrentInstance().router.params;
      let params = {
        id,
        userId: user?.id || ''
      }
      let result = await api.forumController.findDetail(params);
      if (result.success) {
        action.commonChange([
          { paths: 'main.detail', value: result.data },
        ]);
      }
    },
    /**
     * 查询评论列表
     */
    async findCommentList() {
      let { pageNum, commentList } = getData().main;
      let { user } = Taro.getStorageSync('b2b-wechat@login')
      let { id, type } = getCurrentInstance().router.params;
      action.commonChange('main.isLoading', true);
      let params = {
        userId: user?.id || '',
        forumid: id,
        pageNum,
        sort: 1,
      };
      let result = await api.forumController.findCommentList(params);
      if (result.success) {
        action.commonChange('main.isLoading', false);
        if (pageNum == 1) {
          action.commonChange('main.commentList', result.data.rows);
          action.commonChange('main.totalPages', result.data.totalPage);
        } else {
          let newList = commentList.concat(result.data.rows);
          action.commonChange('main.commentList', newList);
          action.commonChange('main.totalPages', result.data.totalPage);
        }
      }
    },
    async addThumb(params) {
      await api.forumController.addThumb(params);
    },
    async deleteThumb(params) {
      await api.forumController.deleteThumb(params);
    },
    async addComment(params) {
      let result = await api.forumController.addComment(params);
      if (result.success) {
        this.findCommentList()
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageBCommunityDetailMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
